package com.taijihuabao.common.rabbitmq;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author changhui.tu
 */
@Configuration
public class RabbitmqConfig {

    /**
     * 提取常量
     *
     * @return
     */
    public static final String EXCHANGE_MESSAGE_SEND = "messageSend_direct";
    public static final String EXCHANGE_DEAD_LETTER = "deadLetter_direct";
    public static final String QUEUE_MAIL_SEND = "emailSend_queue";
    public static final String QUEUE_DEAD_LETTER = "deadLetter_queue";
    public static final String ROUTING_KEY_EMAIL = "email";
    public static final String ROUTING_KEY_DEAD_LETTER = "dead_letter";

    /**
     * 定义邮件交换机
     * 使用Direct订阅模式
     */
    @Bean
    public DirectExchange exchange() {
        return new DirectExchange(EXCHANGE_MESSAGE_SEND);
    }

    /**
     * 死信交换机
     *
     * @return
     */
    @Bean
    public DirectExchange deadLetterExchange() {
        return new DirectExchange(EXCHANGE_DEAD_LETTER);
    }

    /**
     * 定义邮件队列
     * 设置非持久化、非排他、自动删除的队列
     */
    @Bean
    public Queue mailQueue() {
        Map<String, Object> arguments = new HashMap<>(16);
        //声明该队列的死信消息发送到的 交换机 （队列添加了这个参数之后会自动与该交换机绑定，并设置路由键，不需要开发者手动设置)
        arguments.put("x-dead-letter-exchange", EXCHANGE_DEAD_LETTER);
        arguments.put("x-dead-letter-routing-key", ROUTING_KEY_DEAD_LETTER);
        return new Queue(QUEUE_MAIL_SEND, true, false, true, arguments);
    }

    /**
     * 死信队列
     *
     * @return
     */
    @Bean
    public Queue deadLetterQueue() {
        return new Queue(QUEUE_DEAD_LETTER);
    }

    /**
     * 定义绑定
     * 将邮件队列绑定到指定交换机上，并设置routing_key
     */
    @Bean
    public Binding binding() {
        return BindingBuilder.bind(mailQueue()).to(exchange()).with(ROUTING_KEY_EMAIL);
    }

    /**
     * 死信队列绑定死信交换机
     *
     * @return
     */
    @Bean
    public Binding deadLetterBinding() {
        return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange()).with(ROUTING_KEY_DEAD_LETTER);
    }

}

